defmodule EliPhxPlay.Context.UserRelationship do

  @moduledoc """
  用户关系模块
  负责处理用户关系相关的逻辑
  """
  import Ecto.Query, warn: false
  alias EliPhxPlay.Repo
  alias EliPhxPlay.ChatSchema.UserRelationships
  alias EliPhxPlay.ChatSchema.Users

  @doc """
  创建用户关系
  relationship_status的值为pending, accepted, blocked
  默认值为pending
  """
  def create_user_relationship(attrs \\ %{}) do
    %UserRelationships{}
    |> UserRelationships.changeset(attrs)
    |> Repo.insert()
  end

  @doc """
  获取用户关系
  """
  def get_user_relationship(id) do
    Repo.get(UserRelationships, id)
  end

  @doc """
  通过对应id的pending关系并创建反向accepted关系
  """
def accept_user_relationship(id) do
  case get_user_relationship(id) do
    nil ->
      {:error, :relationship_not_found}

    relationship ->
      if relationship.relationship_status == "pending" do
        # 使用事务确保两个操作都成功
        Repo.transaction(fn ->
          # 创建反向关系
          case create_user_relationship(%{
            user_a_id: relationship.user_b_id,
            user_b_id: relationship.user_a_id,
            relationship_status: "accepted"
          }) do
            {:ok, _reciprocal} ->
              # 更新原关系状态
              case update_user_relationship(relationship, %{relationship_status: "accepted"}) do
                {:ok, _updated} ->
                  :accepted
                {:error, changeset} ->
                  Repo.rollback(changeset)
              end
            {:error, changeset} ->
              Repo.rollback(changeset)
          end
        end)
        |> case do
          {:ok, :accepted} -> {:ok, :accepted}
          {:error, changeset} -> {:error, changeset}
        end
      else
        {:error, :invalid_relationship}
      end
  end
end


  @doc """
  查询用户所有accepted关系并获取对应用户信息
  """
  def get_accepted_relationships_with_user_info(user_id) do
    from(r in UserRelationships,
      join: u in Users, on: r.user_b_id == u.user_id,
      where: r.user_a_id == ^user_id and r.relationship_status == "accepted",
      select: %{
        relationship_id: r.relationship_id,
        user_a_id: r.user_a_id,
        user_b_id: r.user_b_id,
        relationship_status: r.relationship_status,
        inserted_at: r.inserted_at,
        user_account: u.account,
        user_nickname: u.nickname,
        user_avatar_url: u.avatar_url
      }
    )
    |> Repo.all()
  end


  @doc """
  查询用户所有的pending关系
  """
  def get_pending_relationships(user_id) do
    query = from u in UserRelationships,
      where: u.user_a_id == ^user_id and u.relationship_status == "pending"
    Repo.all(query)
  end

  @doc """
  查询用户pending关系的数量
  """
  def get_pending_relationships_count(user_id) do
    query = from u in UserRelationships,
      where: u.user_b_id == ^user_id and u.relationship_status == "pending"
    Repo.aggregate(query, :count, :relationship_id)
  end

  @doc"""
  查询用户accepted关系的数量
  """
  def get_accepted_relationships_count(user_id) do
    query = from u in UserRelationships,
      where: u.user_a_id == ^user_id and u.relationship_status == "accepted"
    Repo.aggregate(query, :count, :relationship_id)
  end

  @doc """
  更新用户关系
  """
  def update_user_relationship(%UserRelationships{} = user_relationship, attrs) do
    user_relationship
    |> UserRelationships.changeset(attrs)
    |> Repo.update()
  end

  @doc """
  查询a用户于b用户的pending关系
  """
  def get_user_relationship_by_users(user_a_id, user_b_id) do
    query = from u in UserRelationships,
      where: u.user_a_id == ^user_a_id and u.user_b_id == ^user_b_id and u.relationship_status == "pending"
    Repo.one(query)
  end

  @doc """
  查询用户a在关系中处于b的pending关系
  """
  def get_user_relationship_by_users_b(user_id) do
    query = from u in UserRelationships,
      where: u.user_b_id == ^user_id and u.relationship_status == "pending"
    Repo.all(query)
  end

    # 在 UserRelationship 模块中
  def get_pending_relationships_with_user_info(user_id) do
    from(r in UserRelationships,
      join: u in Users, on: r.user_a_id == u.user_id,
      where: r.user_b_id == ^user_id and r.relationship_status == "pending",
      select: %{
        relationship_id: r.relationship_id,
        user_a_id: r.user_a_id,
        user_b_id: r.user_b_id,
        relationship_status: r.relationship_status,
        inserted_at: r.inserted_at,
        user_account: u.account,
        user_nickname: u.nickname,
        user_avatar_url: u.avatar_url
      }
    )
    |> Repo.all()
  end



end
